import { IRootReducerState } from '@/store/root-reducer';
import { encrypt } from '@/utils/crypto';
import * as api from './auth-api';
import { authSlice } from './auth-slice';
import Cookies from 'js-cookie';

const { actions } = authSlice;
const tenantName = '上海电气';

export const captchaAndToken = (params: any) => async (dispatch: any) => {
  dispatch(actions.start());
  try {
    // const tenantResponse = await api.fetchTenantByName(tenantName);
    // const { data, code } = tenantResponse.data;
    // if (code === 0) {
    //   await dispatch(actions.setTenantId(data));
    // }
    await dispatch(actions.setTenantId(1));

    const response = await api.getCaptchaTypeAndToken(params);
    const { success, repData } = response.data;
    if (success) {
      dispatch(
        actions.persistToken({
          token: repData.token,
          secretKey: repData.secretKey,
        })
      );

      const originBase64 = await fetch(`data:image/jpeg;base64,${repData.originalImageBase64}`);
      const origin = await originBase64.blob();
      const originUrl = URL.createObjectURL(origin);

      const jigsawBase64 = await fetch(`data:image/jpeg;base64,${repData.jigsawImageBase64}`);
      const jigsaw = await jigsawBase64.blob();
      const jigsawUrl = URL.createObjectURL(jigsaw);
      return {
        bgUrl: originUrl,
        puzzleUrl: jigsawUrl,
      };
    }
  } catch (err) {
    dispatch(actions.catchError({ error: err }));
  } finally {
    dispatch(actions.end());
  }
};

export const VerifyCaptcha = (data: any) => async (dispatch: any, getState: () => {}) => {
  dispatch(actions.start());
  try {
    const { auth } = <IRootReducerState>getState();

    const verifyParams = {
      captchaType: 'blockPuzzle',
      token: auth.token,
      pointJson: auth.secretKey
        ? encrypt(JSON.stringify({ x: parseInt(data.x), y: 5.0 }), auth.secretKey)
        : JSON.stringify({ x: parseInt(data.x), y: 5.0 }),
    };

    const response = await api.verifyCaptcha(verifyParams);
    const { success, repData, repMsg } = response.data;
    return success;
  } catch (err) {
    dispatch(actions.catchError({ error: err }));
  } finally {
    dispatch(actions.end());
  }
};

export const login = (params: any) => async (dispatch: any, getState: () => {}) => {
  dispatch(actions.start());

  return api
    .login(params)
    .then(async (response) => {
      const { mrktcoopToken, ltpaToken } = response.data;
      Cookies.set('LtpaToken', ltpaToken, {
        domain: '.shanghai-electric.com',
      });
      await dispatch(actions.setUserToken(mrktcoopToken));
      return mrktcoopToken;
    })
    .catch((err) => {
      dispatch(actions.catchError({ error: err.response.data.message }));
    })
    .finally(() => {
      dispatch(actions.end());
    });
};

export const logout = () => async (dispatch: any) => {
  dispatch(actions.userLogout());
};

export const getCurrentUserInfo = (mrktcoopToken: string) => async (dispatch: any) => {
  dispatch(actions.start());
  try {
    const response = await api.currentUser(mrktcoopToken);

    dispatch(actions.setUserInfo(response.data));

    return true;
  } catch (err) {
    dispatch(actions.catchError({ error: err }));
  } finally {
    dispatch(actions.end());
  }
};

export const updatePreference = (key: string, value: any) => async (dispatch: any, getState: () => {}) => {
  const {
    auth: { preference },
  } = <IRootReducerState>getState();
  dispatch(actions.updatePreference({ ...preference, [key]: value }));
};

export const getCurrentUserOrganizes = () => async (dispatch: any) => {
  dispatch(actions.start());
  try {
    const response = await api.getCurrentOrgList();
    const { code, data } = response.data;
    if (code === 0 && data.length > 0) {
      dispatch(actions.setOrganizes(data));
    }
    return code === 0;
  } catch (err) {
    dispatch(actions.catchError({ error: err }));
  } finally {
    dispatch(actions.end());
  }
};

export const updateOrganizeId = (organizeId: number) => async (dispatch: any) => {
  dispatch(actions.setOrganizeId(organizeId));
};
